# Base64是网络上最常见的用于传输8Bit编码的二进制数据的方法之一 常用于将二进制数据编码成文本数据。
# Base64的工作原理是将3个字节的二进制数据转换为4个字节的二进制数据，其中包含了换行符、空格、加号和字母A~Z，共64个字符，因此称之为Base64。
import base64
from django.http import HttpResponse, FileResponse


import io
import os

# 验证码
from random import choice, randint
# genderate validate code image
from PIL import Image, ImageDraw, ImageFont

class Result:


    def __init__(self, code, msg, data):
        self.code = code
        self.msg = msg
        self.data = data

    def serialize(self):
        return {'code': self.code, 'msg': self.msg, 'data': self.data}



# genrate response contain image data as return value
def read_img(path):
	# 获取图片数据
	with open(path, 'rb') as f:
		img_data = f.read()
		# 将图片数据作为HttpResponse的返回值
		# response = HttpResponse(img_data, content_type='image/*')
		# response['Content-Disposition'] = 'attachment; filename="%s"' % path
		# return response
		return img_data

def download_file(hotel_name, path):
    # 二进制文件内容
    file_content = read_img(path)

    # 设置HttpResponse对象，并设置content_type为文本类型
    response = HttpResponse(file_content, content_type='image/*')

    # 设置文件名
    response['Content-Disposition'] = 'attachment; filename="' + hotel_name + '"'

    return response


def byte_to_img(content):
	# content = '二进制数据'

	byte_stream = io.BytesIO(content)  # 请求数据转化字节流

	roiImg = Image.open(byte_stream)  # Image打开二进制流Byte字节流数据

	imgByteArr = io.BytesIO()  # 创建一个空的Bytes对象

	roiImg.save(imgByteArr, format='JPG')  # PNG就是图片格式

	imgByteArr = imgByteArr.getvalue()  # 保存的二进制流

	return imgByteArr

	# path = '存储文件目录'

	# name = 'test.png'

	# # 生成文件目录
	# if not os.path.exists(path):
	#     os.makedirs(path)

	# # 创建图片
	# with open(path+name, "wb+") as f:
	#     f.write(imgByteArr)










# ============ 验证码 ==========================


# 生成字符串
def getRandomChar():
    num = str(randint(0, 9))
    lower = chr(randint(97, 122))
    upper = chr(randint(65, 90))
    char = choice([num, lower, upper])
    return char


# 生成验证码  串保存在 session 的 'randomcode'
def createImg(request):
    img = Image.new(mode="RGB", size=(160, 30), color=(100, 100, 100))
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(font='arial.ttf', size=24)  # 字体文件在应用目录
    code = ''
    for i in range(5):  # 5个字符的随机串
        c = getRandomChar()
        draw.text((10 + 30 * i, 2), text=c, fill=(255, 255, 255), font=font)
        code += c
        request.session['randomcode'] = code
    f = open("test.png", 'wb')
    img.save(f, format="png")
    f.close()
    return FileResponse(open("test.png", 'rb'))  # 保存图片并返回
